import Docxtemplater from "docxtemplater";
import * as fs from "fs";
import * as  path from "path";
import PizZip from "pizzip";

export const convertDocx = async (template: string, output: string, data: any) => {
  console.log(`转换开始======`);
  console.log(`模板路径：${template} 模版是否存在：${fs.existsSync(template)}`);
  // Load the docx file as binary content
  const content = fs.readFileSync(path.resolve(template), "binary");

  const zip = new PizZip(content);
  const ImageModule = require("docxtemplater-image-module-free");
  const imageOptions = {
    // centered: true,
    getImage(tagValue: string, _tagName: string) {
      return fs.readFileSync(path.resolve(tagValue));
    },
    getSize() {
      return [110, 50];
    }
  };

  const doc = new Docxtemplater(zip, {
    // paragraphLoop: true,
    // linebreaks: true,
    modules: [new ImageModule(imageOptions)]
  });

  // Render the document (Replace {first_name} by John, {last_name} by Doe, ...)
  doc.render(data);

  const buf = doc.getZip().generate({
    type: "nodebuffer",
    // compression: DEFLATE adds a compression step.
    // For a 50MB output document, expect 500ms additional CPU time
    compression: "DEFLATE"
  });

  // buf is a nodejs Buffer, you can either write it to a
  // file or res.send it with express for example.
  fs.writeFileSync(path.resolve(output), buf);
};

function base64DataURLToArrayBuffer(dataURL: string) {
  const base64Regex = /^data:image\/(png|jpg|svg|svg\+xml);base64,/;
  if (!base64Regex.test(dataURL)) {
    return false;
  }
  const stringBase64 = dataURL.replace(base64Regex, "");
  let binaryString;
  if (typeof window !== "undefined") {
    binaryString = window.atob(stringBase64);
  } else {
    binaryString = new Buffer(stringBase64, "base64").toString("binary");
  }
  const len = binaryString.length;
  const bytes = new Uint8Array(len);
  for (let i = 0; i < len; i++) {
    const ascii = binaryString.charCodeAt(i);
    bytes[i] = ascii;
  }
  return bytes.buffer;
}
